<template>
	<xn-form-container title="模版上传" :width="400" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-row :gutter="24">
			<a-col :span="24">
				<a-spin :spinning="uploadLoading">
					<a-upload-dragger
						ref="uploadRef"
						:before-upload="handleBeforeUpload"
						v-model:file-list="fileList"
						:show-upload-list="true"
						:headers="headers"
						accept=".xlsx, .xls, .csv, .docx, .doc"
						:auto-upload="false"
						multiple
					>
						<p class="ant-upload-drag-icon">
							<inbox-outlined />
						</p>
						<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
						<p class="ant-upload-hint">支持单个上传</p>
					</a-upload-dragger>
				</a-spin>
			</a-col>
		</a-row>
		<a-divider />
		<a-form ref="formRef" :model="formData" :rules="formRules">
			<a-form-item label="模版类型" name="type">
				<a-select v-model:value="formData.type" placeholder="请选择模版类型" :options="yesOrNoOptions" />
			</a-form-item>
			<a-form-item label="模版名称" name="templateName">
				<a-input v-model:value="formData.templateName" placeholder="请输入模版名称" maxlength="10" allowClear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>
<script setup>
	import tool from '@/utils/tool'
	import { message } from 'ant-design-vue'
	import excelTemplateApi from '@/api/tjzy/excel/template/excelTemplateApi'
	import { required } from '@/utils/formRules'

	const emit = defineEmits({ successful: null })
	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	const visible = ref(false)
	const formRef = ref()
	// 表单数据
	const formData = ref({
		type: undefined,
		templateName: undefined
	})
	const formRules = {
		type: [required('请选择模版类型')],
		templateName: [required('请输入模版名称')]
	}
	const yesOrNoOptions = tool.dictList('EXCEL_TEMPLATE_TYPE')
	const uploadLoading = ref(false)
	const fileList = ref([])
	const uploadRef = ref()
	// 打开抽屉
	const openUpload = () => {
		visible.value = true
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		formRef.value.resetFields()
		fileList.value = []
		emit('successful')
	}
	const handleBeforeUpload = () => {
		console.log('beforeUpload')
		return false
	}
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			if (fileList.value.length === 0) {
				message.warn('未选择文件')
				return
			}
			const fileData = new FormData()
			fileData.append('multipartFile', fileList.value[0].originFileObj)
			fileData.append('excelTemplateAddBo', new Blob([JSON.stringify(formData.value)], { type: 'application/json' }))
			excelTemplateApi
				.importExcel(fileData)
				.then(() => {
					emit('successful')
					message.success('批量导入成功') // 在这里显示成功消息
				})
				.finally(() => {
					uploadLoading.value = false
				})
			onClose()
		})
	}
	defineExpose({
		openUpload
	})
</script>
<style scoped></style>
